package us.nchu.tomtiger.dao;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import us.nchu.tomtiger.model.Collection;
import us.nchu.tomtiger.rowMapper.CollectionRowMapper;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by XiongXuan on 2018/1/10.
 */
@Repository
public class CollectionDao {
    @Resource
    private JdbcTemplate jdbcTemplate;

    public boolean insert(Collection collection) {
        String sql = "insert into collect(phone_number, project_id) values(?,?);";

        return jdbcTemplate.update(sql, new Object[]{collection.getPhoneNumber(), collection.getProjectId()})>0;
    }

    public Collection query(String phoneNumber, int projectId) {
        String sql = "select * from collect where phone_number=? and project_id=? and status=1;";

        return (Collection)jdbcTemplate.queryForObject(sql, new Object[]{phoneNumber, projectId},
                new CollectionRowMapper());
    }

    public Collection query(String phoneNumber, String projectId) {
        String sql = "select * from collect where phone_number=? and project_id=? and status=1;";

        return (Collection)jdbcTemplate.queryForObject(sql, new Object[]{phoneNumber, projectId},
                new CollectionRowMapper());
    }

    public boolean delete(String phoneNumber, int projectId) {
        String sql = "update collect set status=0 where phone_number=? and project_id=?";

        Object[] objects = new Object[]{
                phoneNumber,
                projectId
        };

        return jdbcTemplate.update(sql, objects) > 0;
    }

    public List<Collection> queryByUserForList(String phoneNumber) {
        String sql = "select * from collect where phone_number=? and status=1;";
        Object[] objects = new Object[]{
                phoneNumber
        };

        return jdbcTemplate.query(sql, objects, new CollectionRowMapper());
    }

    public List<Collection> queryByProjectForList(String projectId) {
        String sql = "select * from collect where project_id=? and status=1;";
        Object[] objects = new Object[]{
                projectId
        };

        return jdbcTemplate.queryForList(sql, objects, Collection.class);
    }

    public List<Collection> queryByProjectForList(int projectId) {
        String sql = "select * from collect where project_id=? and status=1;";
        Object[] objects = new Object[]{
                projectId
        };

        return jdbcTemplate.queryForList(sql, objects, Collection.class);
    }
}
